package com.hoperun.common.util;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.beanutils.ConversionException;
import org.apache.commons.beanutils.Converter;

public class DateConverter implements Converter
{
	private Object defaultValue;
	 private boolean useDefault;
	
	 public DateConverter()
	 {
		 this.defaultValue = null;
		 this.useDefault = false;
	 }
	 
	 public DateConverter(Object defaultValue)
	 {
		 this.defaultValue = defaultValue;
		 this.useDefault = true;
	 }
	 
	 public Object convert(Class cls, Object value)
	 {
		 if(value == null)
		 {
			 if(this.useDefault)
			 {
				 return this.defaultValue;
			 }
			 return null;
		 }
		 if(value instanceof String)
		 {
			 String s = value.toString();
			 if(s == null || "".equals(s))
			 {
				 return null;
			 }
			DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
			try
			{
				return formatter.parse(s);
				
			}catch(Exception ex)
			{
				throw new ConversionException(ex);
			}				 
		 }
		 if(value instanceof Date)
		 {
			 return (Date)value;
		 }
		 if(value instanceof Long)
		 {
			 return new Date(((Long)value).longValue());
		 }
		 return null;
	 }
	 
	 /**
	  * 
	  * @param date
	  * @param format
	  * @return
	  * 
	  */
	 public static String DateToStr(Date date, String format){
		 DateFormat formatter = new SimpleDateFormat(format);
		 return formatter.format(date);
	 }
	 
	 /**
	  * 
	  * @param date
	  * @param format
	  * @return

	  */
	 public static String sqlDateToStr(java.sql.Date date, String format){
		 DateFormat formatter = new SimpleDateFormat(format);
		 return formatter.format(date);
	 }	 
	 
}
